﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BGParallax : MonoBehaviour
{
    public int controlNum = 4;
    public float parallaxScale = 0.5f;
    public float layerFactor = 0.4f;
    public float smooth = 8;

    private Transform cam;
    private Transform[] bgTrans;
    private Vector3 lastCamPos;
    
    // Start is called before the first frame update
    void Start()
    {
        bgTrans = new Transform[controlNum];
        cam = Camera.main.transform;
        lastCamPos = cam.position;
        for (int i = 0; i < controlNum; i++)
        {
            bgTrans[i] = transform.GetChild(i);
            //Debug.Log(bgTrans[i].name);
        }
    }

    // Update is called once per frame
    void Update()
    {
        float parallax = (lastCamPos.x - cam.position.x) * parallaxScale;
        for(int i = 0; i < controlNum; i++)
        {
            float nowX = bgTrans[i].position.x;
            float newX = nowX + (1 + i) * layerFactor * parallax;
            bgTrans[i].position = new Vector3(
               Mathf.Lerp(nowX, newX, smooth * Time.deltaTime), bgTrans[i].position.y, bgTrans[i].position.z);
        }
        lastCamPos = cam.position;
    }
}
